package com.glela.talent.service.impl;

import com.glela.platform.util.UserUtil;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.cxf.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.glela.common.constant.CommonConstants;
import com.glela.common.constant.KeepAccountsTypeConstants;
import com.glela.common.util.DateUtil;
import com.glela.common.util.DateUtils;
import com.glela.common.util.OrderUtil;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.CUserMoneyChangeMapper;
import com.glela.platform.mapper.ChangeProcessLogMapper;
import com.glela.platform.mapper.CheckCodeMapper;
import com.glela.platform.mapper.RedeemCodeLogMapper;
import com.glela.platform.mapper.RedeemCodeMapper;
import com.glela.platform.mapper.UserInfoMapper;
import com.glela.platform.mapper.UserJournalMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.UserMoneyMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.CUserMoneyChange;
import com.glela.platform.model.ChangeProcessLog;
import com.glela.platform.model.CheckCode;
import com.glela.platform.model.PushMessage;
import com.glela.platform.model.RedeemCode;
import com.glela.platform.model.User;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserMoney;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.PushMessageService;
import com.glela.platform.service.UserMoneyService;
import com.glela.platform.service.UserPromotionService;
import com.glela.talent.mapper.BackMoneyTempMapper;
import com.glela.talent.mapper.OrderVipMapper;
import com.glela.talent.mapper.TalentActiveLogMapper;
import com.glela.talent.mapper.TalentMapper;
import com.glela.talent.mapper.VipExpensesMapper;
import com.glela.talent.model.BackMoneyTemp;
import com.glela.talent.model.OrderVip;
import com.glela.talent.model.VipExpenses;
import com.glela.talent.service.TalentService;
import com.glela.talent.service.UserDailyLogService;
import com.glela.talent.util.MyDateUtil;
import com.glela.usermoney.mapper.UserCommisionMapper;
import com.glela.usermoney.model.UserCommision;

/**
 * @author MaoZeYao
 */
@Service("talentService")
@Scope("singleton")
public class TalentServiceImpl implements TalentService {

  @Autowired
  private TalentMapper talentMapper;

  @Autowired
  private TalentActiveLogMapper talentActiveLogMapper;

  @Autowired
  private UserMapper userMapper;

  @Autowired
  private UserInfoMapper userInfoMapper;

  @Autowired
  private UserPromotionService userPromotionService;

  @Autowired
  private VipExpensesMapper vipExpensesMapper;

  @Autowired
  private OrderVipMapper orderVipMapper;

  @Autowired
  private PushMessageService pushMessageService;

  @Autowired
  private CheckCodeMapper checkCodeMapper;

  @Autowired
  UserDailyLogService userDailyLogService;

  @Autowired
  private BackMoneyTempMapper backMoneyTempMapper;

  //	@Autowired
//	private UnifiedTreatmentService unifiedTreatmentService;
  @Autowired
  private RedeemCodeMapper redeemCodeMapper;
  @Autowired
  private RedeemCodeLogMapper redeemCodeLogMapper;
  @Autowired
  private ChangeProcessLogMapper LogMapper;

  @Autowired
  private UserMoneyService userMoneyService;

  private MyDateUtil util = MyDateUtil.INSTANCE;

  //ZYF
  @Autowired
  private BaseRestrictionsService baseRestrictionsService;

  //gaoweiqi

  @Autowired
  private UserMoneyMapper userMoneyMapper;
  @Autowired
  private UserCommisionMapper userCommisionMapper;
  @Autowired
  private UserJournalMapper userJournalMapper;
  @Autowired
  private CUserMoneyChangeMapper moneyChangeMapper;

  /**
   * 外部使用 判定会员等级 校妆身份判定身份判定
   */
  public int userIdentityJudge(int experience, int totalSales, int roleId) throws Exception {
    // roleId 1普通用户 2会员（校妆） 3达人S1 4达人S2 5达人S3 6达人S4 7达人导师
    //type : 加上所引，保证查询效率

    if (roleId == 4) {
      return 4;
    }
    BaseRestrictions baseRestrictions = baseRestrictionsService
        .selectAllBaseRestrictionsByType("upgrade_store_ grade_value");
    //暂时注释满1000升级为标准店逻辑
    if (Objects.equals(baseRestrictions, null)) {
      throw new Exception("未设置标准店升级业绩标准！");
    }
    //upgrade_store_grade_value 小白店铺升级为标准店铺的业绩门槛：单位：分
    int upgrade_store_grade_value = baseRestrictions.getRestrictions();
    if (totalSales >= 0 && totalSales <= (upgrade_store_grade_value - 1)) {
      return 3;
    }
    // 经验值大于600 销售额2000 - 5000 s2

    if (totalSales >= upgrade_store_grade_value
        && totalSales <= CommonConstants.SYSTEM_MAX_TOTAL_AMOUNT) {
      return 4;
    }
    return roleId;
  }

  /**
   * 欲购身份判定
   */
  public int userIdentityJudgeYG(int experience, int totalCost) {
    // 2达人S0 3达人S1 4达人S2 5达人S3 6达人S4
    if (experience <= 600 && experience >= 0 && totalCost >= 600) {
      return 0;
    }
    return 0;
  }

  /**
   * 根据激活码激活达人 (校妆) 达人导师身份不可覆盖
   */
  @Override
  public ResponseEntity<?> activationTalentByRedeemCode(Long userId, String redeemCode)
      throws Exception {
    // 根据ID查询用户是否存在
    User user = userMapper.selectUserEntityById(userId);
    if (user == null) {
      // 用户不存在
      return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
    }
    if (user.getRoleId() >= 3) {
      // 已经是达人了
      return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30114), HttpStatus.OK);
    }
    // 查询兑换码的详情
    RedeemCode redeemCodePo = redeemCodeMapper.selectRedeemCodeByRedeemCode(redeemCode);
    // 查询兑换码日志
    int userCodeStatus = talentActiveLogMapper
        .selectUserCodeStatusByUserId(userId, redeemCodePo.getRedeemCode());
    if (userCodeStatus > 0) {
      // 您已经使用过该兑换码了
      return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30102), HttpStatus.OK);
    }
    // 兑换码日期比对
    int dateStatus = DateUtil.betweenTime(redeemCodePo.getStartDate(), redeemCodePo.getEndDate());
    if (dateStatus == 0) {
      // 兑换码已经过期
      return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30103), HttpStatus.OK);
    }
    // 4.判断兑换码的可用次数 104
    if (redeemCodePo.getUsedTimes() >= redeemCodePo.getUsableTimes()) {
      // 此激活码的次数已用尽
      return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30101), HttpStatus.OK);
    }
    // 如果兑换码的激活人没有推荐人身份则将当前兑换码的推荐人的身份填入 推荐人身份不可覆盖
    if ("".equals(user.getTalentTeacher()) || user.getTalentTeacher() == null) {
      // 3.查询兑换码的主人判断状态 103
      int refereesId = talentMapper.selectRefereesIdByPromotionId((redeemCodePo.getPromotionId()));
      // 取出激活码主人的身份ID
      UserInfo referees = userInfoMapper.selectUserInfoEntityByUserId(refereesId);
      /*
			 * 2016 - 10 -14 放入推荐人身份
			 * user.setRecommendFrom(referees.getRecommendFrom());
			 */
      user.setTalentTeacher(referees.getPersionId());
      user.setRecommendFrom(referees.getPersionId());
    }

    // 5.满足以上条件则激活达人 103
    if (StringUtils.isEmpty(user.getTalentEffectTime())) {
      user.setTalentEffectTime(redeemCodePo.getEndDate());
    } else {
      boolean useThis = util.betweenTwoDate(redeemCodePo.getEndDate(), user.getTalentEffectTime());
      if (useThis) {
        user.setTalentEffectTime(redeemCodePo.getEndDate());
      }
    }

    // 身份换算 , 修改用户等级 ，此部分注释， 用户等级修改，移至订单支付成功之后 ， 这里原来的逻辑根据经验值升级 ，现在既然销售额 ，那么应该放在订单支付成功之后。
//		int roleId = userIdentityJudge(user.getEmpiricValue(), user.getTotalCost(), user.getRoleId());
//		int activeStatus = talentMapper.updateUserTalentByUserId(user.getId(), roleId, redeemCodePo.getStartDate(),	redeemCodePo.getEndDate(), user.getTalentTeacher());
//		if (activeStatus <= 0) {
//			throw new Exception();
//		}
    // 推荐人身份变为自己
    UserInfo userInfo = userInfoMapper.selectByUserId(userId);
    userMapper.updateRecommendFromById(userInfo.getPersionId(), userId);

    //开始记录日志
    ChangeProcessLog Log = new ChangeProcessLog();
    Log.setDescription("根据激活码激活达人");
    Log.setMethod("TalentServiceImpl.activationTalentByRedeemCode");
    Log.setPrimaryID(String.valueOf(userId));
    Log.setTableName("yg_user.c_user");
    Log.getBeforeMap().put("recommendFrom", user.getRecommendFrom());
    Log.getAfterMap().put("recommendFrom", userInfo.getPersionId());
    LogMapper.insert(Log);

    // 更新兑换码的使用次数
    redeemCodeMapper
        .updateRedeemCodeUsedTimesById(redeemCodePo.getId(), redeemCodePo.getUsedTimes() + 1);
    // 插入用户使用兑换码记录
    redeemCodeLogMapper.insertRedeemCodeLog(redeemCodePo.getId(), user.getId());
    // 新增兑换码激活日志
    int activeLog = talentActiveLogMapper
        .insertIntoUserActiveTalentByRedeemCode(userId, redeemCode);
    if (activeLog <= 0) {
      throw new Exception();
    }
    return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
  }

  /**
   * 达人经验值修改 达人升级
   */
  @Override
  public ResponseEntity<?> increaseTalentExperience(Long userId, int experince) throws Exception {
    User user = userMapper.selectUserEntityById(userId);
    if (user == null) {
      // 用户不存在
      return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
    }

    if (user.getRoleId() > 2 && user.getRoleId() < 7) {
      user.setEmpiricValue(user.getEmpiricValue() + experince);
      //计算用户的总销售额
//			int totelSale = unifiedTreatmentService.userSalesAmountTotal(userId);
//          根据用户总销售额，计算用户的等级 roleId ， 之前的逻辑是根据用户经验值在这里计算，现在是根据销售额，那没有必要在这里计算。注释后，放在订单支付成功那里进行计算。
//			int roleId = userIdentityJudge(user.getEmpiricValue(), totelSale, user.getRoleId());
//			int updateRole = talentMapper.updateTalentRoleIdByUserId(user.getId(), roleId, user.getEmpiricValue());
//			if (updateRole <= 0) {
//				throw new Exception();
//			}

      // 修改推荐人身份为自己
      UserInfo userInfo = userInfoMapper.selectByUserId(userId);
      userMapper.updateRecommendFromById(userInfo.getPersionId(), userId);

      //开始记录日志
      ChangeProcessLog Log = new ChangeProcessLog();
      Log.setDescription("达人升级");
      Log.setMethod("TalentServiceImpl.increaseTalentExperience");
      Log.setPrimaryID(String.valueOf(userId));
      Log.setTableName("yg_user.c_user");
      Log.getBeforeMap().put("recommendFrom", user.getRecommendFrom());
      Log.getAfterMap().put("recommendFrom", userInfo.getPersionId());
      LogMapper.insert(Log);

      return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
    }

    int updateStatus = talentMapper.updateTalentExpericeByUserId(userId, experince);
    if (updateStatus <= 0) {
      throw new Exception();
    }
    return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
  }

  /**
   * 普通用户成交导师链接激活会员身份 1.用户身份从普通用户升级成为会员 2.会员推荐人身份变成导师的身份 3.只有导师才可以覆盖会员推荐人身份
   *
   * @throws Exception
   */
//	@Override
//	public ResponseEntity<?> activationVipFromTeacherFrist(Long userId, Long teacherId) throws Exception {
//		User user = userMapper.selectUserEntityByIdNoPassword(userId);
//		User teacher = userMapper.selectUserEntityByIdNoPassword(teacherId);
//		if (user == null || teacher == null) {
//			// 用户不存在
//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
//		}
//		// roleId 1普通用户 2会员（校妆） 3达人S1 4达人S2 5达人S3 6达人S4 7达人导师
//		if (user.getRoleId() >= 2) {
//			// 方法调错了
//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30113), HttpStatus.OK);
//		}
//		if (teacher.getRoleId() != 7) {
//			// 此导师ID无效
//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30115), HttpStatus.OK);
//		}
//		UserInfo teacherInfo = userInfoMapper.selectUserInfoEntityByUserId(teacherId);
//		user.setMemberRecommend(teacherInfo.getPersionId());
//		int activeStatus = talentMapper.updateVipUserByTeacherFirst(userId, 2, util.formatString(new Date()),
//				util.getYear("2049-12-30 00:00:00"), user.getMemberRecommend());
//		if (activeStatus <= 0) {
//			throw new Exception();
//		}
//		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
//	}

  /**
   * 会员成交导师转发的链接
   */
//	@Override
//	public ResponseEntity<?> changeTeacherMemberRecommend(Long userId, Long teacherId) throws Exception {
//		User user = userMapper.selectUserEntityByIdNoPassword(userId);
//		User teacher = userMapper.selectUserEntityByIdNoPassword(teacherId);
//		if (user == null || teacher == null) {
//			// 用户不存在
//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
//		}
//		// roleId 1普通用户 2会员（校妆） 3达人S1 4达人S2 5达人S3 6达人S4 7达人导师
//		if (user.getRoleId() == 1) {
//			// 方法错误
//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30114), HttpStatus.OK);
//		}
//		if (user.getRoleId() > 2) {
//			// 此方法不适用于达人
//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30114), HttpStatus.OK);
//		}
//		if (teacher.getRoleId() != 7) {
//			// 此导师ID无效
//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30115), HttpStatus.OK);
//		}
//		UserInfo teacherInfo = userInfoMapper.selectUserInfoEntityByUserId(teacherId);
//		user.setMemberRecommend(teacherInfo.getPersionId());
//		int activeStatus = talentMapper.updateVipUserByTeacherCommon(userId, user.getMemberRecommend());
//		if (activeStatus <= 0) {
//			throw new Exception();
//		}
//		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
//	}

  /**
   * 激活会员,记录日志并推送客户端消息
   */
  public ResponseEntity<?> activationUserVip(Long userId, Long money) throws Exception {
    //记录日志
    User u = userMapper.selectByPrimaryKey(userId);
    if (u == null) {
      return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
    }
    ChangeProcessLog Log = new ChangeProcessLog();
    Log.setDescription("激活会员");
    Log.setMethod("TalentServiceImpl.activationUserVip");
    Log.setPrimaryID(String.valueOf(userId));
    Log.setTableName("yg_user.c_user");
    Log.getBeforeMap().put("Role", u.getRoleId());
    Log.getAfterMap().put("Role", 2);
    LogMapper.insert(Log);

    int activeStatus = userMapper.updateVipUserByUserId(userId, 2, util.formatString(new Date()),
        util.getYear("2049-12-30 00:00:00"));
    if (activeStatus <= 0) {
      throw new Exception();
    }
    // 激活日志
    int actLog = talentActiveLogMapper.insertIntoUserActiveTalentByMoney(userId, money);
    if (actLog <= 0) {
      throw new Exception();
    }
    // 发放会员礼包
    if (money > 0) {
      userPromotionService.giveGiftPackageToVIP(userId);
      // 推送消息
      PushMessage pushMessage = new PushMessage();
      pushMessage.setIsAll(0);
      pushMessage.setUserId(userId);
      pushMessage.setStatus(1);
      pushMessage.setTitle("购买成功");
      pushMessage.setContent("恭喜您成功购买会员获得会员礼包一份，请至我的钱包查收。");
      pushMessage.setType(1);
      pushMessageService.autoPushMessage(pushMessage);

      return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
    }
    return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
  }

  @Override
  public OrderVip createOrderVip(long userId, int payType) throws Exception {
    VipExpenses vipExpenses = vipExpensesMapper.selectVipExpensesEntity();
    // 生成订单
    OrderVip orderVip = new OrderVip();
    orderVip.setOrderSn("V" + OrderUtil.getOrderSn());// 生成订单号
    orderVip.setVipExpensesId(vipExpenses.getId());// 关联商品
    orderVip.setExpenseName(vipExpenses.getExpenseName());// 商品名称
    orderVip.setUserId(userId);// 关联用户ID
    orderVip.setSalePrice(vipExpenses.getMoney());// 售价
    orderVip.setTotalPrice(vipExpenses.getMoney());// 总价格
    orderVip.setSumNumber(1);// 数量
    orderVip.setCashCoin(0);// 现金币
    orderVip.setTotalFee(vipExpenses.getMoney());// 实际支付金额
    orderVip.setCommisionFee(0);// 分佣无
    orderVip.setPayDate(DateUtil.toString(new Date()));// 支付时间
    orderVip.setPayType(payType);
    orderVip.setIsBill(0);
    orderVip.setBillType(0);
    orderVip.setStatus(1);
    int insertStatus = orderVipMapper.insertIntoOrderVip(orderVip);
    if (insertStatus <= 0) {
      throw new Exception();
    }
    return orderVip;
  }

  @Override
  public int recommendUserRegister(String userName, String code, String recommendFrom,
      String nickName,
      String picture, int sex) throws Exception {
    User user = userMapper.selectUserByUserName(userName);
    if (user != null) {
      // 用户已经注册
      int i = 2;
      return i;
    }
    CheckCode checkcode = checkCodeMapper.selectCheckCodeByMobile(userName);
    if (!checkcode.getCode().equals(code)) {
      // 验证码不正确
      int i = 3;
      return i;
    }
    if (StringUtils.isEmpty(recommendFrom)) {
      // 校妆姐姐店铺的店主ID
      Integer storeUserId = this.baseRestrictionsService.getBaseRestrictionsForCache("xz_jj")
          .getExperience();
      // 默认普通推荐人身份为校妆姐姐
      if (storeUserId != null) {
        UserInfo xzjjUserInfo = userInfoMapper.selectByUserId(Long.valueOf(storeUserId));
        if (xzjjUserInfo != null) {
          recommendFrom = xzjjUserInfo.getPersionId();
        }
      }
    }
	/*
		int sign = userInfoMapper.selectUserinfoMaxSign();
		if (sign <= 0) {
			sign = 100000;
		}
		sign += 1;
		String persionId = RandomUtil.getRandomStr(2) + sign;*/
    int i = userMapper.insertUser(userName, "", recommendFrom, nickName, picture);
    User user1 = userMapper.selectUserByUserName(userName);
    // 检查是否存在usermoney信息
    userMoneyService.checkExistUserMoney(user1.getId());

    userInfoMapper.insertUserInfo(user1.getId(), UserUtil.getPersonId(user1.getId()),
        user1.getId().intValue(), sex);
    if (i == 1) {
      UserInfo userInfo = userInfoMapper.selectUserInfoByPersion(recommendFrom);
      // 推荐用户增加经验值 10
      userMapper.updateUserEmpiricValue(userInfo.getUserId(), 10);
      // 增加用户日常操作日志 并增加经验值判断是否升级
      userDailyLogService.addUserDailyLog(userInfo.getUserId(), 3);
      //开始记录日志
      ChangeProcessLog Log = new ChangeProcessLog();
      Log.setDescription("推荐注册");
      Log.setMethod("TalentServiceImpl.recommendUserRegister");
      Log.setPrimaryID("");
      Log.setTableName("yg_user.c_user");
      Log.getAfterMap().put("recommendFrom", recommendFrom);
      LogMapper.insert(Log);
    }
    return i;
  }

  /**
   * 返还现金币
   */
  @Transactional(propagation = Propagation.REQUIRED)
  @Override
  public void autoBackMoney(int startIndex, int pageSize) {
    List<BackMoneyTemp> waitDeal = backMoneyTempMapper.selectBackMoneyData(startIndex, pageSize);
    int count = 0;
    for (BackMoneyTemp dealOne : waitDeal) {
      User user = userMapper.selectUserByUserName(dealOne.getUserName());
      if (user != null) {
        List<UserMoney> userMoney = userMoneyMapper.selectAllByUserIdAndType(user.getId(), 1);//账户余额
        if (userMoney != null && userMoney.size() == 1) {
          UserMoney userMoneyTemp = userMoney.get(0);
          int newMoney = userMoneyTemp.getNormalAmount().intValue() + dealOne.getMoney();
          // 生成事务
          UserCommision c = new UserCommision();
          c.setUserId(user.getId());//用户ID
          c.setFee(dealOne.getMoney());//余额付
          c.setIsCustom(0);//是否手工
          c.setStatus(1);
          c.setResult(1);
          c.setResultTime(DateUtils.dateFormat(new Date(), "YYYY-MM-dd hh:mm:ss"));
          c.setComment("11月嗨购返现"); //备注
          c.setBusinessTypeId(10);//类型id
          c.setBusinessTypeName("嗨购返现处理");//类型名字
          long timeS = System.currentTimeMillis();
          c.setSourceId(timeS);
          count = userCommisionMapper.insertSelective(c);
          UserCommision temp = userCommisionMapper.selectBySourceIDAndType(timeS, 10);
          if (count > 0 && temp != null) {//插入成功 增加余额 生成流水
            count = userMoneyMapper.increaseUserAmount(user.getId(), 1, dealOne.getMoney());
            if (count > 0) {//更新成功 生成流水和资产变化
              backMoneyTempMapper.updateBackMoneyTempById(dealOne.getId(),
                  "SUCCESS-LOCALMONEY：" + userMoneyTemp.getNormalAmount(), newMoney);
              UserJournal balanceJournal = new UserJournal();
              balanceJournal.setUserId(user.getId());
              balanceJournal.setMoney(temp.getFee());
              balanceJournal.setType("+");
              balanceJournal.setComment("11月嗨购返现");
              balanceJournal.setStatus(6); // 系统返还
              balanceJournal.setBusinessTypeId(10);
              balanceJournal.setBusinessTypeName("嗨购返现处理");
              balanceJournal.setIsDelete(0);
              balanceJournal.setCommisionId(temp.getId().intValue());
              balanceJournal.setKeepAccountsType(KeepAccountsTypeConstants.COMMISSION_HGFH);
              count = userJournalMapper.insertSelective(balanceJournal);
              if (count > 0) {
                UserJournal ResultBalanceJournal =
                    userJournalMapper.getUserJournalBySourceIDandBusinessType(
                        temp.getId(), 10);
                // 记录用户资产的变化
                CUserMoneyChange MoneyChange = new CUserMoneyChange();
                MoneyChange.setUserId(user.getId());
                MoneyChange.setOrderSn((long) ResultBalanceJournal.getId());// 源ID
                MoneyChange.setChangeAmount(dealOne.getMoney());
                MoneyChange.setNormalBeforAmount(userMoneyTemp.getNormalAmount());
                MoneyChange.setNormalAfterAmount(userMoneyTemp.getNormalAmount()
                    + ResultBalanceJournal.getMoney());
                MoneyChange.setSourceType(Byte.valueOf("1"));//amount
                MoneyChange.setFreeBeforAmount(userMoneyTemp.getFrozenAmount());
                MoneyChange.setFreeAfterAmount(userMoneyTemp.getFrozenAmount());
                MoneyChange.setChangeFreeAmount(0);
                moneyChangeMapper.insertSelective(MoneyChange);
              }
            }
          }
        }
      } else {
        backMoneyTempMapper.updateBackMoneyTempById(dealOne.getId(),
            "FALL:Un find User:" + dealOne.getUserName(), 0);
      }
    }
  }

}
